﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

using WorkStation.Frameworks.Core.Data.DataTableValidate;

namespace WorkStation.Frameworks.Core.Data.Extensions
{
    /// <summary>
    /// * DataTable扩展类
    /// </summary>
    public static class DataTableExtensions
    {
        /// <summary>
        /// * DataTable转化为实体
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="sTable">数据源</param>
        /// <returns></returns>
        public static List<TEntity> ToList<TEntity>(this DataTable sTable) 
        {
            List<TEntity> res = new List<TEntity>();

            foreach (DataRow row in sTable.Rows) 
            {
                TEntity entity = Activator.CreateInstance<TEntity>();

                foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties()) 
                {
                    if (sTable.Columns.Cast<DataColumn>().SingleOrDefault(v => v.ColumnName.Equals(propertyInfo.Name)) != null) 
                    {
                        object value = row[propertyInfo.Name];
                        
                        value = DataReaderExtensions.AdaptType(value, propertyInfo.PropertyType);

                        propertyInfo.SetValue(entity, value, null);
                    }
                }
            }
            
            return res;
        }

        public static List<ValidateResult> Validate(this DataTable table, IValidateSpecification spec) 
        {
            return spec.Validate(table);
        }
    }
}
